function Connect4() {
    this.grid = Array.from({ length: 6 }, (_, j) => (Array.from({ length: 7 }, (_, i) => 0)));
    this.cur_player = 1;
    this.has_finished = false;
};

Connect4.prototype.isWon = function () {
    //horizonal
    for (row of this.grid) {
        if (new RegExp(`${this.cur_player}{4,}`).test(row.join(''))) return `Player ${this.cur_player} wins!`
    }
    //vertical
    for (var j = 0; j < this.grid[0].length; j++) {
        var colum = this.grid.map(v => v[j]);
        if (new RegExp(`${this.cur_player}{4,}`).test(colum.join(''))) return `Player ${this.cur_player} wins!`
    }
    var ROW = this.grid.length;
    var COL = this.grid[0].length;
    //diagonals
    for (var row = 0; row < ROW; row++) {
        var temp = [];
        for (var i = row, j = 0; i < ROW && j < COL; i++, j++) {
            temp.push(this.grid[i][j]);
        }
        if (new RegExp(`${this.cur_player}{4,}`).test(temp.join(''))) return `Player ${this.cur_player} wins!`
    }
    for (var col = 0; col < COL; col++) {
        var temp = [];
        for (var j = col, i = 0; i < ROW && j < COL; i++, j++) {
            temp.push(this.grid[i][j]);
        }
        if (new RegExp(`${this.cur_player}{4,}`).test(temp.join(''))) return `Player ${this.cur_player} wins!`
    }

    for (var row = 0; row < ROW; row++) {
        var temp = [];
        for (var i = row, j = COL - 1; i < ROW && j > -1; i++, j--) {
            temp.push(this.grid[i][j]);
        }
        if (new RegExp(`${this.cur_player}{4,}`).test(temp.join(''))) return `Player ${this.cur_player} wins!`
    }

    for (var col = COL - 1; col > -1; col--) {
        var temp = [];
        for (var j = col, i = 0; i < ROW && j > -1; i++, j--) {
            temp.push(this.grid[i][j]);
        }
        if (new RegExp(`${this.cur_player}{4,}`).test(temp.join(''))) return `Player ${this.cur_player} wins!`
    }
    return false;
}

Connect4.prototype.isColumnFull = function (col) {
    return this.grid.map(v => v[col]).indexOf(0) === -1
}

Connect4.prototype.play = function (col) {
    if (this.has_finished) return 'Game has finished!';
    if (this.isColumnFull(col)) return 'Column full!';
    for (var i = this.grid.length - 1; i > -1; i--) {
        if (this.grid[i][col] === 0) {
            this.grid[i][col] = this.cur_player;
            var temp = this.cur_player;
            var result = this.isWon();
            if (result) { this.has_finished = true; return result; }
            this.cur_player = this.cur_player === 1 ? 2 : 1;
            return `Player ${temp} has a turn`;
        }
    }
};